class AIWriter {
    constructor() {
        this.editor = document.querySelector('#text');
        this.proxyUrl = window.AIWriterConfig.proxyUrl;
        this.init();
    }

    init() {
        this.createButton();
        this.createDialog();
    }

    createButton() {
        const toolbar = document.querySelector('.submit');
        if (!toolbar) return;

        const button = document.createElement('button');
        button.type = 'button';
        button.className = 'ai-writer-btn';
        button.innerHTML = `
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5"></path>
            </svg>
            AI写作
        `;
        button.onclick = () => this.openDialog();
        
        toolbar.parentNode.insertBefore(button, toolbar);
    }

    createDialog() {
        const dialog = document.createElement('div');
        dialog.className = 'ai-writer-dialog';
        dialog.style.display = 'none';
        dialog.innerHTML = `
            <div class="dialog-header">
                <div class="dialog-title">AI 写作助手</div>
                <button class="dialog-close">&times;</button>
            </div>
            <div class="dialog-body">
                <div class="writing-options">
                    <button class="ai-writer-btn" data-action="continue">续写内容</button>
                    <button class="ai-writer-btn" data-action="custom">按要求写作</button>
                </div>
                <div class="chat-input" style="display: none;">
                    <textarea placeholder="请输入写作要求..."></textarea>
                    <button class="ai-writer-btn">生成内容</button>
                </div>
                <div class="generated-content"></div>
            </div>
        `;

        const overlay = document.createElement('div');
        overlay.className = 'ai-writer-overlay';
        overlay.style.display = 'none';

        document.body.appendChild(overlay);
        document.body.appendChild(dialog);

        this.dialog = dialog;
        this.overlay = overlay;
        this.generatedContent = dialog.querySelector('.generated-content');
        this.input = dialog.querySelector('textarea');
        this.sendButton = dialog.querySelector('.chat-input button');

        // 绑定事件
        dialog.querySelector('.dialog-close').onclick = () => this.closeDialog();
        overlay.onclick = () => this.closeDialog();
        this.sendButton.onclick = () => this.sendMessage();
        this.input.onkeydown = (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                this.sendMessage();
            }
        };

        // 添加新的事件绑定
        dialog.querySelectorAll('.writing-options button').forEach(btn => {
            btn.onclick = () => this.handleWritingOption(btn.dataset.action);
        });
    }

    openDialog() {
        this.dialog.style.display = 'block';
        this.overlay.style.display = 'block';
        // 触发动画
        requestAnimationFrame(() => {
            this.dialog.classList.add('show');
            this.overlay.classList.add('show');
        });
    }

    closeDialog() {
        this.dialog.classList.remove('show');
        this.overlay.classList.remove('show');
        // 等待动画结束后隐藏
        setTimeout(() => {
            this.dialog.style.display = 'none';
            this.overlay.style.display = 'none';
        }, 200);
    }

    async sendMessage() {
        const message = this.input.value.trim();
        if (!message) return;

        // 直接调用 generateContent
        await this.generateContent(message);
        this.input.value = '';
    }

    async generateContent(prompt) {
        this.generatedContent.innerHTML = '<div class="message-content">正在生成内容...</div>';
        
        try {
            const response = await fetch(this.proxyUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    message: prompt,
                    context: this.editor.value
                })
            });

            if (!response.ok) throw new Error('请求失败');

            // 处理流式响应
            const reader = response.body.getReader();
            let content = '';
            const contentElement = this.generatedContent.querySelector('.message-content');

            while (true) {
                const {done, value} = await reader.read();
                if (done) break;

                const text = new TextDecoder().decode(value);
                const lines = text.split('\n');
                
                for (const line of lines) {
                    if (line.startsWith('data: ')) {
                        const data = JSON.parse(line.slice(6));
                        content += data.result;
                        contentElement.textContent = content;
                    }
                }
            }

            // 添加插入按钮
            contentElement.insertAdjacentHTML('afterend', `
                <button class="ai-writer-btn" onclick="aiWriter.insertToEditor(this.previousElementSibling)">
                    插入编辑器
                </button>
            `);

        } catch (error) {
            console.error('AI写作请求失败:', error);
            this.generatedContent.innerHTML = '<div class="message-content">生成失败，请稍后重试</div>';
        }
    }

    insertToEditor(contentEl) {
        const content = contentEl.textContent;
        const cursorPos = this.editor.selectionStart;
        const text = this.editor.value;
        
        this.editor.value = text.slice(0, cursorPos) + content + text.slice(cursorPos);
        this.closeDialog();
    }

    handleWritingOption(action) {
        const inputArea = this.dialog.querySelector('.chat-input');
        if (action === 'continue') {
            inputArea.classList.remove('show');
            setTimeout(() => {
                inputArea.style.display = 'none';
                this.generateContent(this.editor.value + '\n继续写作...');
            }, 200);
        } else {
            inputArea.style.display = 'flex';
            requestAnimationFrame(() => {
                inputArea.classList.add('show');
            });
        }
    }
}

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    window.aiWriter = new AIWriter();
});